/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package utils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 科泰集团教研团队
 * @version 1.0.0
 * @fileName RequestUtil.java
 */
public class RequestUtil {

    /**
     * 转换长整数参数
     * @param request
     * @param name
     * @param defaultVal
     * @return
     */
    public static Long parseLong(HttpServletRequest request, String name, Long defaultVal){
        String value = request.getParameter(name);
        if(value != null && !value.trim().isEmpty()){
            try {
                return Long.parseLong(value.trim());
            }catch (Exception e){}
        }
        // 如果转换失败返回默认值
        return defaultVal;
    }

    /**
     * 转换整数参数
     * @param request
     * @param name
     * @param defaultVal
     * @return
     */
    public static Integer parseInt(HttpServletRequest request, String name, Integer defaultVal){
        String value = request.getParameter(name);
        if(value != null && !value.trim().isEmpty()){
            try {
                return Integer.parseInt(value.trim());
            }catch (Exception e){}
        }
        // 如果转换失败返回默认值
        return defaultVal;
    }

    /**
     * 转换单精度浮点数参数
     * @param request
     * @param name
     * @param defaultVal
     * @return
     */
    public static Float parseFloat(HttpServletRequest request, String name, Float defaultVal){
        String value = request.getParameter(name);
        if(value != null && !value.trim().isEmpty()){
            try {
                return Float.parseFloat(value.trim());
            }catch (Exception e){}
        }
        // 如果转换失败返回默认值
        return defaultVal;
    }

    /**
     * 转换双精度浮点数参数
     * @param request
     * @param name
     * @param defaultVal
     * @return
     */
    public static Double parseDouble(HttpServletRequest request, String name, Double defaultVal){
        String value = request.getParameter(name);
        if(value != null && !value.trim().isEmpty()){
            try {
                return Double.parseDouble(value.trim());
            }catch (Exception e){}
        }
        // 如果转换失败返回默认值
        return defaultVal;
    }

    /**
     * 按指定格式转换日期参数
     * @param request
     * @param name
     * @param defaultVal
     * @param dateFormat
     * @return
     */
    public static Date parseDate(HttpServletRequest request, String name, Date defaultVal,
                                 String dateFormat){
        String value = request.getParameter(name);
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        if(value != null){
            try {
               return sdf.parse(value);
            }catch (Exception e){}
        }
        return defaultVal;
    }

}
